package com.attendancesystem.controller;


import com.attendancesystem.service.UserService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "DetailUserController", value = "/DetailUserController")
public class CheckUserInfoController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JsonNode rootNode = objectMapper.readTree(request.getReader());
        PrintWriter out = response.getWriter();
        String username = rootNode.get("userName").asText();
        String role = rootNode.get("role").asText();
//        System.out.println(username);
//        System.out.println(role);
        UserService userService = new UserService();
        Object userDetail =userService.editUser(username,role);
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("role", role);
            result.put("data", userDetail);
            objectMapper.writeValue(response.getWriter(),result);


        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            objectMapper.writeValue(response.getWriter(),
                    Collections.singletonMap("error", "服务器内部错误"));
        }

    }
}
